package com.cow.controller;

import java.io.File;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cow.mapper.UserMapper;
import com.cow.pojo.User;
import com.cow.pojo.UserAddress;
import com.cow.service.FriendService;
import com.cow.service.UserService;
import com.cow.util.FileUtil;
import com.cow.util.PhoneFormatCheckUtils;
import com.cow.util.SendMessageUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author 光环and鬼泣
 * @version 2018年5月24日 上午10:41:39
 */
@Api(description = "用户接口")
@Controller
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private FriendService friendService;

	/**
	 * @param req
	 * @param rep
	 * @Description 发送短信
	 * @RequestParam tel 手机号
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "发送短信接口", notes = "发送短信接口")
	@ResponseBody
	@RequestMapping(value = "/sendMessage.action", method = RequestMethod.POST)
	public JSONObject sendMessage(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("registerPhone") String registerPhone) throws Exception {
		JSONObject datas = new JSONObject();
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(registerPhone)) {
			String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
			HttpSession session = req.getSession();
			session.setAttribute("code", code);
			session.setAttribute("tel", registerPhone);
			Boolean result = SendMessageUtil.sendMessage(registerPhone, code);
			User user = userService.getUser(registerPhone);
			if (user == null) {
				if (result) {
					datas.put("result", "短信发送成功");
					datas.put("code", "1");
				} else {
					datas.put("result", "短信发送失败");
					datas.put("code", "0");
				}
			} else {
				datas.put("result", "手机号已被注册，请更换手机号");
				datas.put("code", "-2");
			}
		} else {
			datas.put("code", "-1");
			datas.put("result", "手机号填写有误，请填写正确规范的手机号");
		}

		return datas;

	}

	/**
	 * @param req
	 * @param rep
	 * @Description 登录
	 * @RequestParam userName 账号
	 * @RequestParam password 密码
	 * @throws Exception
	 */
	@ApiOperation(value = "用户注册接口", notes = "用户注册接口")
	@ResponseBody
	@RequestMapping(value = "/register.action", method = RequestMethod.POST)
	public JSONObject register(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("registerPhone") String registerPhone, @RequestParam("password") String password,
			@RequestParam("code") String code) throws Exception {
		JSONObject datas = new JSONObject();
		if (registerPhone == null || password == null || code == null) {
			datas.put("result", "请将登录信息填写完整");
			datas.put("code", "0");
		} else {
			HttpSession session = req.getSession();
			String code1 = String.valueOf(session.getAttribute("code"));
			String tel = String.valueOf(session.getAttribute("tel"));
			if (tel.equals(registerPhone) && code1.equals(code)) {
				User user = new User();
				int img = 1 + (int) (Math.random() * 4);
				String userAvatarurl = "http://halo.natapp1.cc/cow/userImg/" + String.valueOf(img) + ".jpg";
				user.setUserAvatarurl(userAvatarurl);
				user.setUserId(String.valueOf(UUID.randomUUID()));
				user.setUserName(registerPhone);
				user.setUserPassword(password);
				user.setUserLevel(1);
				user.setUserExp(1);
				user.setUserType("tel");
				user.setUserNickname(registerPhone);
				session.setAttribute("userId", user.getUserId());
				int result = userService.insertUser(user);
				if (result == 1) {
					datas.put("result", "注册成功");
					datas.put("code", "1");
				} else {
					datas.put("result", "注册失败");
					datas.put("code", "0");
				}
			} else {
				datas.put("result", "验证码错误");
				datas.put("code", "-1");
			}
		}
		return datas;
	}

	@ApiOperation(value = "用户登录接口", notes = "用户登录接口")
	@ResponseBody
	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	public JSONObject login(HttpServletRequest req, HttpServletResponse rep, @RequestParam("phone") String phone,
			@RequestParam("password") String password) throws Exception {
		JSONObject datas = new JSONObject();
		User user = userService.getUser(phone);
		if (user != null) {
			HttpSession session = req.getSession();
			session.setAttribute("userId", user.getUserId());
			if (user.getUserPassword().equals(password)) {
				datas.put("result", "登陆成功");
				datas.put("code", "1");
				datas.put("userId", user.getUserId());
			} else {
				datas.put("result", "用户名或密码错误");
				datas.put("code", "-1");
			}
		} else {
			datas.put("result", "未注册用户");
			datas.put("code", "-2");
		}
		return datas;

	}

	@ApiOperation(value = "获取用户信息", notes = "获取用户信息")
	@ResponseBody
	@RequestMapping(value = "/getUserById.action", method = RequestMethod.POST)
	public JSONObject getUserById(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("userId") String userId) throws Exception {
		User user = userService.getUserbyId(userId);
		JSONObject userJSON = new JSONObject();
		userJSON.put("user", user);
		return userJSON;

	}

	@ApiOperation(value = "修改用户信息", notes = "修改用户信息")
	@ResponseBody
	@RequestMapping(value = "/updateUser.action", method = RequestMethod.POST)
	public JSONObject updateUser(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("userAvatarUrl") String userAvatarUrl, @RequestParam("nickName") String nickName,
			@RequestParam("userId") String userId) throws Exception {
		User user = userService.getUserbyId(userId);
		if (userAvatarUrl != null) {
			String filePath = req.getServletContext().getRealPath("upload");
			File files = FileUtil.GenerateImage(userAvatarUrl, filePath);
			String fileUploadPath = FileUtil.fileUpload(files);
			if (user.getUserAvatarurl() != null) {
				FileUtil.fileDelete(user.getUserAvatarurl());
			}
			user.setUserAvatarurl(fileUploadPath);
		}
		if (nickName != null) {
			user.setUserNickname(nickName);
		}
		int result = userService.updataUser(user);
		JSONObject datas = new JSONObject();
		if (result == 1) {
			datas.put("result", "修改成功");
			datas.put("code", "1");
		} else {
			datas.put("result", "修改失败");
			datas.put("code", "0");
		}
		return datas;

	}

	@ApiOperation(value = "获取用户好友列表", notes = "获取用户好友列表")
	@ResponseBody
	@RequestMapping(value = "/getFriendList.action", method = RequestMethod.POST)
	public JSONObject getFriendList(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("userId") String userId) throws Exception {
		List<User> friendList = friendService.getFriendList(userId);
		JSONObject result = new JSONObject();
		result.put("friendList", JSONArray.fromObject(friendList));
		return result;
	}

	@ApiOperation(value = "新增用户收货地址", notes = "新增用户收货地址")
	@ResponseBody
	@RequestMapping(value = "/setUserAddress.action", method = RequestMethod.POST)
	public JSONObject setUserAddress(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("userId") String userId, @RequestParam("address") String address,
			@RequestParam("userName") String userName, @RequestParam("userTel") String userTel) throws Exception {
		UserAddress userAddress = new UserAddress();
		userAddress.setAddress(address);
		userAddress.setUserId(userId);
		userAddress.setUserName(userName);
		userAddress.setUserTel(userTel);
		userAddress.setAddressId(String.valueOf(UUID.randomUUID()));
		List<UserAddress> userAddressesList = userService.getUseraddressList(userId);
		for (UserAddress userAddress1 : userAddressesList) {
			if (userAddress1.getDefaultStatus().equals("是")) {
				userAddress1.setDefaultStatus("否");
				userService.updataUseraddress(userAddress1);
			}
		}
		userAddress.setDefaultStatus("是");
		int result = userService.insertUseraddress(userAddress);
		JSONObject datas = new JSONObject();
		if (result == 1) {
			datas.put("result", "添加收货地址成功");
			datas.put("code", "1");
		} else {
			datas.put("result", "添加收货地址失败");
			datas.put("code", "0");
		}
		return datas;

	}

	@ApiOperation(value = "修改用户收货地址", notes = "修改用户收货地址")
	@ResponseBody
	@RequestMapping(value = "/updataUserAddress.action", method = RequestMethod.POST)
	public JSONObject updataUserAddress(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("addressId") String addressId, @RequestParam("address") String address,
			@RequestParam("userName") String userName, @RequestParam("userTel") String userTel) throws Exception {
		UserAddress userAddress = userService.getUseraddress(addressId);
		if (address != null && address != "") {
			userAddress.setAddress(address);
		}
		if (userName != null && userName != "") {
			userAddress.setUserName(userName);
		}
		if (userTel != null && userTel != "") {
			userAddress.setUserTel(userTel);
		}
		int result = userService.updataUseraddress(userAddress);
		JSONObject datas = new JSONObject();
		if (result == 1) {
			datas.put("result", "修改收货地址成功");
			datas.put("code", "1");
		} else {
			datas.put("result", "修改收货地址失败");
			datas.put("code", "0");
		}
		return datas;

	}

	@ApiOperation(value = "获取用户收货地址列表", notes = "获取用户收货地址列表")
	@ResponseBody
	@RequestMapping(value = "/getUserAddress.action", method = RequestMethod.POST)
	public JSONObject getUserAddress(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("userId") String userId) throws Exception {
		List<UserAddress> userAddressList = userService.getUseraddressList(userId);
		JSONObject datas = new JSONObject();
		datas.put("userAddressList", userAddressList);
		return datas;
	}

	@ApiOperation(value = "设置用户默认收货地址", notes = "设置用户默认收货地址")
	@ResponseBody
	@RequestMapping(value = "/setDefaultUserAddress.action", method = RequestMethod.GET)
	public JSONObject setDefaultUserAddress(HttpServletRequest req, HttpServletResponse rep,
			@RequestParam("addressId") String addressId) throws Exception {
		UserAddress userAddress = userService.getUseraddress(addressId);
		userAddress.setDefaultStatus("是");
		int result = 0;
		List<UserAddress> userAddressList = userService.getUseraddressList(userAddress.getUserId());
		for (UserAddress userAddress1 : userAddressList) {
			if(userAddress1.getDefaultStatus().equals("是")) {
				userAddress1.setDefaultStatus("否");
				result = result + userService.updataUseraddress(userAddress1);
				break;
			}
		}
		result = result + userService.updataUseraddress(userAddress);
		JSONObject datas = new JSONObject();
		if (result == 2) {
			datas.put("result", "更改默认收货地址成功");
			datas.put("code", "1");
		} else {
			datas.put("result", "更改默认收货地址失败");
			datas.put("code", "0");
		}
		return datas;

	}
}
